﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebLibrary;
using VirtualBank.Data.Entities;

namespace WebRoot
{
    public partial class AccountEditor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AccountType.DataSource = Utility.AccountTypes;
                AccountType.DataTextField = "Value";
                AccountType.DataValueField = "Key";
                AccountType.DataBind();

                AccountsList.DataSource = (from a in Master.DataContext.Accounts
                                           select a);
                AccountsList.DataBind();
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            Account newAccount = new Account();
            newAccount.Description = AccountDescription.Text;
            newAccount.AccountNumber = AccountNumber.Text;
            newAccount.AccountType = byte.Parse(AccountType.SelectedValue);
            newAccount.Username = Username.Text;
            newAccount.Password = String.IsNullOrWhiteSpace(Password.Text) ?
                String.Empty : Utility.EncryptStringAES(Password.Text, "secret");
            newAccount.Website = Website.Text;
            newAccount.OpeningBalance = String.IsNullOrWhiteSpace(OpeningBalance.Text) ? 
                null : (decimal?)decimal.Parse(OpeningBalance.Text);
            newAccount.InterestRate = String.IsNullOrWhiteSpace(InterestRate.Text) ?
                null : (decimal?)decimal.Parse(InterestRate.Text);
            
            Master.DataContext.Accounts.InsertOnSubmit(newAccount);
            Master.DataContext.SubmitChanges();

            AccountsList.DataSource = (from a in Master.DataContext.Accounts
                                       select a);
            AccountsList.DataBind();
        }

        protected void AccountsList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            (e.Item.FindControl("AccounType") as Literal).Text = Utility.AccountTypes[(e.Item.DataItem as Account).AccountType];
        }
    }
}